<template>
    <div class="body1">
        <div class="no-print el-button-print">
            <el-button @click="exportPDF">导出为pdf</el-button>
        </div>

        <div class="body2" id="pdfDom" :class="{ 'pdf-export': isPdfExport }">
            <div class="title">
                <div class="biaotididian">{{ agencyName }}</div>
                <div class="biaoti">回避申请决定书</div>
            </div>
            <div class="tableStyle1">
                <div class="writ-height">
                    <div style="display: inline-block; position: relative;">
                        <span>申&nbsp;请&nbsp;人：</span>
                        <privy-info-select-return-array v-model="form.unitName" :isTable="false" return-fields="A"
                            :return-array-template="[
                                { name: 'companyLicense', field: 'B', },
                                { name: 'legalPerson', field: 'C', },
                                { name: 'legalPersonPhone', field: 'H', },
                            ]" :rowConfig="unitNameConfig" @select="selectUnitUpdateData">
                        </privy-info-select-return-array>
                    </div>
                </div>
                <div class="writ-height">
                    <span>统一社会信用代码：</span>
                    <input v-model="form.companyLicense" :resize="'none'" autosize maxlength="23" class="inputStyle1"
                        style="width: calc(23 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
                </div>
                <div class="writ-height">
                    <span>联&nbsp;系&nbsp;人：</span>
                    <input v-model="form.legalPerson" :resize="'none'" autosize maxlength="10" class="inputStyle1"
                        style="width: calc(10 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
                    <span>联系电话：</span>
                    <input v-model="form.legalPersonPhone" :resize="'none'" autosize maxlength="24" class="inputStyle1"
                        style="width: calc(12 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea"
                        oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')">
                </div>
                <div class="writ-height">
                    <span>被申请人：</span>
                    <InvestigatorSelect class="InvestigatorSelectReplace"
                        style="height: 6mm; width: calc(9 * 5mm);margin-bottom: 4px;border-bottom: 1px solid black"
                        v-model="form.a5" :id-field="'a6'" @change="handleInvestigatorChange" />
                    <span>行政执法证号：</span>
                    <input v-model="form.a6" :resize="'none'" autosize class="inputStyle1" readonly
                        style="width: calc(11 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
                </div>

                <div style="height: 550px; line-height: 30px;">
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;申请人于</span>
                    <editable-textarea :text="form.date1" param-type="YYYYMMDD1" @send-to-parent="receiveFromChild" />
                    <span>以</span>
                    <CrossRowInput v-model:value="form.a7" :line-config="a7Config"></CrossRowInput>
                    <span>为由，申请</span>
                    <input v-model="form.a8" :resize="'none'" autosize maxlength="5" class="inputStyle1"
                        style="width: calc(5 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
                    <span>回避实施</span>
                    <input v-model="form.a9" :resize="'none'" autosize maxlength="28" class="inputStyle1"
                        style="width: calc(28 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
                    <span>行政检查。</span>
                    <br><span>&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" v-model="form.a10">经审查，符合</span>
                    <input v-model="form.a11" :resize="'none'" autosize maxlength="20" class="inputStyle1"
                        style="width: calc(20 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
                    <span>规定的回避情形，同意申请人的回避申请，并将行政执法人员更换为</span>
                    <InvestigatorSelect class="InvestigatorSelectReplace"
                        style="height: 6mm; width: calc(5 * 5mm);margin-bottom: 4px;border-bottom: 1px solid black"
                        v-model="form.a12" :id-field="'a13'" @change="handleInvestigatorChange" />
                    <span>行政执法证号</span>
                    <input v-model="form.a13" :resize="'none'" autosize class="inputStyle1" readonly
                        style="width: calc(11 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
                    <span>。</span>
                    <br><span>&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" v-model="form.a14">经审查，不符合</span>
                    <input v-model="form.a15" :resize="'none'" autosize maxlength="20" class="inputStyle1"
                        style="width: calc(20 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
                    <span>规定的回避情形，驳回申请人的回避申请。</span>
                    <br><span>&nbsp;&nbsp;&nbsp;&nbsp;如对本决定不服，可以依法申请救济。</span>
                </div>
                <div style="text-align: right; margin-top: 10px; margin-bottom: 50px;">
                    <div class="seal-container">
                        <span class="seal-name" v-html="sealName"></span>
                        <div class="delivery-agency-div" :class="{ 'official-seal-display': isDisplay }">
                            <editable-textarea :text="form.date2" param-type="YYYYMMDD2"
                                @send-to-parent="receiveFromChild" />
                            <img class="official-seal" src="../../assets/tupian.png" alt="Image">
                        </div>
                    </div>
                </div>
                <div style="line-height: 30px;">
                    <span>受送达人：</span><input v-model="form.a35" :resize="'none'" autosize maxlength="20"
                        class="inputStyle1" style="width: calc(20 * 5mm);font-family: 仿宋;font-size: 5mm;"
                        type="textarea">
                    <editable-textarea :text="form.date3" param-type="YYYYMMDD3" @send-to-parent="receiveFromChild" />
                    <br><span>送达方式与地址：</span><input v-model="form.a36" :resize="'none'" autosize maxlength="24"
                        class="inputStyle1" style="width: calc(24 * 5mm);font-family: 仿宋;font-size: 5mm;"
                        type="textarea">
                </div>
            </div>
        </div>
    </div>

</template>

<script>
import EditableTextarea from "@/views/template/EditableTextarea";
import { agencyName, sealName } from "../../utils/publicName.js"
import PrivyInfoSelectReturnArray from "@/views/template/PrivyInfoSelectReturnArray.vue";
import CrossRowInput from '@/views/template/CrossRowInput';
import InvestigatorSelect from "@/views/template/InvestigatorSelect.vue";

export default {
    components: {
        EditableTextarea,
        CrossRowInput,
        PrivyInfoSelectReturnArray,
        InvestigatorSelect
    },

    data() {
        return {
            agencyName: agencyName,
            sealName: sealName,
            form: {},
            status: '', //当前文书的状态
            isPdfExport: false, //控制打印样式
            isDisplay: true, //控制官方印章的显示
            unitNameConfig: {
                firstLine: { chars: 27 * 2 },
                middleLines: { count: 0, chars: 32 * 2 },
                lastLine: { chars: 0 * 2 }
            },
            a7Config: {
                firstLine: { chars: 18 * 2 },
                middleLines: { count: 0, chars: 32 * 2 },
                lastLine: { chars: 22 * 2 }
            },
        }
    },

    created() {
        window.parent.getTemplateData((data, status) => {
            this.form = data;
            this.status = status;
        })
        window.postForm = () => {
            this.postForm();
        }
    },

    mounted() {
        window.parent.changeTemplateDow();
    },

    methods: {
        // 导出为pdf
        exportPDF() {
            if (this.status !== '4') {
                this.isDisplay = false
            }
            this.savePDF()
                .then((blob) => {

                    const blobUrl = URL.createObjectURL(blob);

                    // 先预览
                    const previewWindow = window.open(blobUrl, '_blank');

                    // 自动下载
                    const fileName = `回避申请决定书.pdf`;
                    const downloadLink = document.createElement('a');
                    downloadLink.href = blobUrl;
                    downloadLink.download = fileName;
                    document.body.appendChild(downloadLink);
                    downloadLink.click();
                    document.body.removeChild(downloadLink);

                    // 监听预览窗口关闭后释放内存
                    if (previewWindow) {
                        const timer = setInterval(() => {
                            if (previewWindow.closed) {
                                clearInterval(timer);
                                URL.revokeObjectURL(blobUrl);
                            }
                        }, 1000);
                    } else {
                        setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); // 兜底释放
                    }
                })
                .catch(error => {
                    console.error('导出PDF出错:', error);
                    alert('导出失败，请重试或联系管理员');
                });
        },
        savePDF() {
            this.isPdfExport = true; // 激活PDF样式
            return new Promise((resolve, reject) => {
                this.$nextTick(() => {
                    import('html2pdf.js').then((module) => {
                        const html2pdf = module.default;

                        //获取所有需要替换的 el-input
                        const elInputs = document.querySelectorAll('.el-input__inner, .el-textarea__inner');

                        //存储原始元素和它们的父节点，方便后续恢复
                        const originalElements = [];

                        elInputs.forEach((input) => {
                            const div = document.createElement('div');
                            div.style.whiteSpace = 'pre-wrap'; // 保留换行
                            div.style.fontFamily = '仿宋';
                            div.style.fontSize = '5mm';
                            div.textContent = input.value; // 保留原内容（自动处理 \n 换行）
                            div.style.lineHeight = '1.3';

                            // 替换 el-input，并存储原始元素
                            originalElements.push({
                                parent: input.parentNode,
                                original: input,
                                replacement: div,
                            });
                            input.parentNode.replaceChild(div, input);
                        });

                        // 配置选项
                        const opt = {
                            margin: 0,
                            image: {
                                type: 'jpeg',
                                quality: 0.98
                            },
                            html2canvas: {
                                scale: 2,
                                logging: false,
                                useCORS: true
                            },
                            jsPDF: {
                                unit: 'mm',
                                format: 'a4',
                                orientation: 'portrait'
                            }
                        };

                        const element = document.getElementById('pdfDom');

                        // 生成PDF Blob对象
                        html2pdf()
                            .set(opt)
                            .from(element)
                            .toPdf()
                            .get('pdf')
                            .then((pdf) => {
                                const blob = pdf.output('blob');

                                resolve(blob); // 返回Blob对象
                            })
                            .catch((error) => {
                                reject(error);
                            })
                            .finally(() => {
                                this.isPdfExport = false; // 恢复原始样式
                                this.isDisplay = true;
                                // 恢复原始input
                                originalElements.forEach(({ parent, original, replacement }) => {
                                    parent.replaceChild(original, replacement);
                                });
                            });
                    }).catch((error) => {
                        reject(error);
                        this.isPdfExport = false;
                        this.isDisplay = true;
                        originalElements.forEach(({ parent, original, replacement }) => {
                            parent.replaceChild(original, replacement);
                        });
                    });
                });
            });
        },
        //父页面提交按钮将调用此方法，此方法将文书数据回传到父页面的请求方法中
        postForm() {
            this.savePDF()
                .then((blob) => {


                    // 创建FormData并添加文件
                    const formData = new FormData();
                    formData.append('file', blob, '回避申请决定书.pdf');

                    window.parent.postTemplateDate(this.form, formData);
                })
                .catch(error => {
                    console.error('整个保存PDF出错:', error);
                });
        },
        //选择日期时间
        receiveFromChild(data, type) {
            const TypeMap = {
                'YYYYMMDD1': 'date1',
                'YYYYMMDD2': 'date2',
                'YYYYMMDD3': 'date3',
            };
            if (TypeMap[type]) {
                this.form[TypeMap[type]] = data;
            }
        },
        //选择执法人员
        handleInvestigatorChange({ identificationNumber, idField }) {
            if (idField && identificationNumber) {
                this.form[idField] = identificationNumber;
            }
        },
        // 选择单位
        selectUnitUpdateData(data) {
            data.forEach(item => {
                this.form[item.name] = item.value;
            })
        },
    }
}
</script>

<style scoped>
.official-seal {
    /* 公章隐藏*/
    display: none;
    width: 4.2cm;
    height: 4.2cm;
    z-index: 20;

    /* 定位 */
    position: absolute;
    bottom: -20px;
    right: -10px;
}


:deep(.el-button-print .el-button) {
    display: inline-flex !important;
    visibility: visible !important;
    opacity: 1 !important;
    width: auto;
    min-width: 100px;
    height: auto;
    padding: 8px 15px;
    background: #fff !important;
    color: #000 !important;
    border: none;
}

:deep(.el-textarea__inner) {
    box-shadow: 0 0 0 0;
    color: black;
    padding: 0;
    font-family: "仿宋", serif;
    font-size: 19px;
    overflow-y: hidden;
    line-height: 30px;

    /* 下划线 */
    border-radius: 0px;
    background-image: linear-gradient(to top, #000000 0.5px, transparent 1px);
    background-size: 100% 30px;
    background-position: 0 -3px;
}

:deep(.el-textarea-hidden .el-textarea__inner) {
    box-shadow: 0 0 0 0;
    color: black;
    padding: 0;
    font-family: "仿宋", serif;
    font-size: 19px;
    overflow-y: hidden !important;
    resize: none !important;
    height: auto !important;
}

:deep(.el-select .el-input__inner) {
    text-align: center;
    height: 5mm;
}

.input-container {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
}

.inputStyleNoLine {
    border: none;
    outline: none;
    padding: 0px;
}

.typeSpan {
    cursor: pointer;
    font-size: 5mm;
}
</style>
